package org.example;

import org.example.server.internal.Hello;
import org.example.server.impl.HelloServiceImpl;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceRegistration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lianmingzhang
 * @Date: 2022/5/4 16:36
 */
public class Activator implements BundleActivator, ServiceListener {
    private List<ServiceRegistration> registrations = new ArrayList<ServiceRegistration>();

    @Override
    public void start(BundleContext bundleContext) throws Exception {
        System.out.println("----------------hello start---------------------");
        //注册hello接口中的服务
        ServiceRegistration<?> service = bundleContext.registerService(Hello.class.getName(), new HelloServiceImpl("Hello, OSGi"), null);
        registrations.add(service);
        System.out.println("----------------hello start---------------------");

    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        for (ServiceRegistration registration : registrations) {
            registration.unregister();
        }
    }

    @Override
    public void serviceChanged(ServiceEvent serviceEvent) {
        String[] objectClass = (String[])
                serviceEvent.getServiceReference().getProperty("objectClass");

        System.out.println(
                "Ex1: Service of type " + objectClass);
        if (serviceEvent.getType() == ServiceEvent.REGISTERED) {
            System.out.println(
                    "Ex1: Service of type " + objectClass[0] + " registered.");
        } else if (serviceEvent.getType() == ServiceEvent.UNREGISTERING) {
            System.out.println(
                    "Ex1: Service of type " + objectClass[0] + " unregistered.");
        } else if (serviceEvent.getType() == ServiceEvent.MODIFIED) {
            System.out.println(
                    "Ex1: Service of type " + objectClass[0] + " modified.");
        }
    }
}
